import NavBar from '@/components/NavBar';
import styles from './index.module.scss';
import Input from '@/components/Input';
import { useFormik } from 'formik';
import * as yup from 'yup';
import { useDispatch } from 'react-redux';
import { sendCodeAction, loginAction } from '@/store/action/login';
import { useState, useRef, useEffect } from 'react';
import { useHistory, useLocation } from 'react-router-dom';
import { Toast } from 'antd-mobile';
import { LocationStateType } from '@/components/AuthRoute';

export default function Login(props: any) {
  // 设置时间秒数

  const [second, setSecond] = useState(0);
  const history = useHistory();
  const location = useLocation<LocationStateType>();
  const formik = useFormik({
    initialValues: {
      mobile: '17817001700',
      code: '',
    },
    onSubmit: (value) => {
      dispatch(loginAction(value));
      // 登陆成功跳转,如果从登录页来的就回去，给一个空对象
      const { from = '/' } = location.state || {};
      history.push(from);
      // history.push('/');
      Toast.show({ content: '登陆成功' });
    },

    validationSchema: () =>
      yup.object().shape({
        mobile: yup
          .string()
          .required('不能为空')
          .matches(/^1[3-9]\d{9}$/, '手机格式不对'),
        code: yup
          .string()
          .required('不能为空')
          .matches(/^\d{6}$/, '验证码不正确'),
      }),
  });

  const dispatch = useDispatch();
  let timeRef = useRef(-1);
  // 设置数据
  const handleSendCodes = () => {
    setSecond(60);
    dispatch(sendCodeAction(formik.values.mobile));
    // 倒计时
    timeRef.current = window.setInterval(() => {
      //  数据异步的，所以写成箭头函数，可以获取到最新的值
      setSecond((seconTime) => {
        // console.log(seconTime);
        if (seconTime === 1) {
          // 清除定时器
          clearInterval(timeRef.current);
        }
        return seconTime - 1;
      });
    }, 1000);
  };
  // 卸载的时候清除定时器
  useEffect(() => {
    return () => {
      clearInterval(timeRef.current);
    };
  }, []);
  return (
    <div className={styles.root}>
      <NavBar>登录</NavBar>
      <div className="content">
        {/* 标题 */}
        <h3>短信登录</h3>
        <form onSubmit={formik.handleSubmit}>
          {/* 手机号输入框 */}

          {/* 封装的组件 */}
          <Input
            autoFocus
            className="input"
            placeholder="请输入手机号"
            autoComplete="off"
            type="text"
            name="mobile"
            maxLength={11}
            errMsg={formik.touched.mobile ? formik.errors.mobile : ''}
            value={formik.values.mobile}
            onChange={formik.handleChange}
            // 失焦时才校验
            onBlur={formik.handleBlur}
          />
          <Input
            className="test"
            extra={
              second === 0 ? (
                <span
                  onClick={handleSendCodes}
                  // onClick={() => dispatch(sendCodeAction(formik.values.mobile))}
                >
                  获取验证码
                </span>
              ) : (
                second + '后再获取'
              )
            }
            placeholder="请输入验证码"
            autoComplete="off"
            type="text"
            name="code"
            maxLength={6}
            errMsg={formik.touched.code ? formik.errors.code : ''}
            value={formik.values.code}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
          />
          {/* 登录按钮 */}
          <button
            type="submit"
            className="login-btn"
            // 为false则为不禁用
            disabled={!formik.isValid}
          >
            登录
          </button>
        </form>
      </div>
    </div>
  );
}
